import json
import datetime
import time

import jwt
from django.db import IntegrityError
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from jwt import ExpiredSignatureError

from user.models import User
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from utils import responsedata
from django_vue_back import settings


# 用户认证
def user_login(request):
    # post 认证参数json格式
    user_form = CustomerUtils.get_request_data(request)
    # 密码加密
    user_form['password'] = CustomerUtils.md5(user_form['password'])
    db_user = User.objects.filter(**user_form).first()
    if db_user is None:
        # 用户名或密码错误
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message' : '用户名或密码错误'
        }
        return CustomerUtils.response_json(response)

    # 判断用户状态 是否被禁用
    if db_user.active == 0:
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '账号被禁用，请联系管理员'
        }
        return CustomerUtils.response_json(response)

    # 用户认证通过 生成token
    payload = {
        'id' : db_user.id,
        'username' : db_user.username,
        'exp' : datetime.datetime.utcnow() + datetime.timedelta(days=1),
    }

    token = CustomerUtils.create_token(payload, settings.SECRET)

    response = {
        'code' : ResponseStatus.BUSINESS_SUCCESS,
        'message' : '认证通过',
        'data': {
            'token':token
        }
    }
    return CustomerUtils.response_json(response)



# 获取用户信息
def user_info(request):
    if request.method == 'GET':
        token = request.GET.get('token')
        print(token)
        # 反向解析token
        try:
            user_token_dict = CustomerUtils.verify_token(token, settings.SECRET)
            user_id = user_token_dict['id']
            db_user = User.objects.filter(id=user_id).first()
            response = {
                'code': ResponseStatus.BUSINESS_SUCCESS,
                'data':{
                    'name': db_user.username,
                    'avatar': db_user.avatar,
                    'roles':[db_user.role.role_en],
                }
            }
            return CustomerUtils.response_json(response)
        except ExpiredSignatureError as e:
            response = {
                'code' : ResponseStatus.TOKEN_EXPIRED,
                'message' : 'token已失效，请重新认证'
            }
            return CustomerUtils.response_json(response)
        except Exception as e:
            response = {
                'code': ResponseStatus.ILLEGAL_TOKEN,
                'message': 'token异常，请重新认证'
            }
            return CustomerUtils.response_json(response)




# 用户分页数据
def user_page(request):
    # current_page size 接收分页参数
    if request.method == 'POST':
        # {'page': 1, 'size': 5}
        form_data = CustomerUtils.get_request_data(request)
        print(form_data)

        # 空条件
        condition = Q()
        # 动态条件 存在就拼接
        if form_data.get('username').strip():
            # 复杂查询用Q 大小写不敏感icontains
            condition &= Q(username__icontains=form_data['username'])
        if form_data.get('email').strip():
            condition &= Q(email__icontains=form_data['email'])
        if form_data.get('active') != '':
            condition &= Q(active=form_data['active'])


        # 分页处理 传回去total条数 tableData数据
        user_list = User.objects.filter(condition).order_by('-id')
        # 获取分页对象
        paginator = Paginator(user_list, form_data.get('size', 5))
        # 获取数据总条数
        total = paginator.count
        # 当前页对象
        current_page = paginator.page(form_data.get('page', 1))
        # 当前页数据 [{},{},{}]
        table_data = current_page.object_list

        # 查询user有关联表，需要特殊处理
        users = []
        for user in table_data:
            users.append({
                'id': user.id,
                'username': user.username,
                'age': user.age,
                'email': user.email,
                'active': user.active,
                'create_time': user.create_time.strftime('%Y-%m-%d'),
                'role_name' : user.role.role_name,
                'dept_name' : user.dept.dept_name,

            })
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data' : {
                'total': total,
                'tableData': users
            }
        }

        return CustomerUtils.response_json(response)

def user_state(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        User.objects.filter(id=form_data.get('id')).update(active=form_data.get('state'))
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def user_reset_pwd(request, id):
    default_pwd = '111111'
    User.objects.filter(id=id).update(password=CustomerUtils.md5(default_pwd))
    return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)

def user_one(request, id):
    user = User.objects.filter(id=id).first()
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'user': {
                'id': user.id,
                'username': user.username,
                'age': user.age,
                'email': user.email,
                'active': user.active,
                'role_id': user.role_id,
                'dept_id': user.dept_id,
            }
        }
    }
    return CustomerUtils.response_json(response)

def user_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        user_id = form_data.get('id')
        try:
            if user_id is not None:
                # 更新操作
                User.objects.filter(id=user_id).update(**form_data)
            else:
                # 添加用户信息 设置用户密码
                form_data['password'] = CustomerUtils.md5('111111')
                User(**form_data).save()
        except IntegrityError as e:
            response = responsedata.BUSINESS_ERROR_DATA
            response['message'] = str(e)
            return CustomerUtils.response_json(response)
        else:
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def user_batch_remove(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        # 用户没有级联关系，不用捕捉异常直接删
        User.objects.filter(id__in=form_data.get('ids')).delete()
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)